<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :search.sync="search"
      :before-open="beforeOpen"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.laboratoryReport_add" @click="addBtn">新 增</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.laboratoryReport_delete" @click="handleDelete">删 除</el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot-scope="{ row, index }" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" v-if="permission.laboratoryReport_view" @click="rowView(row)">详情</el-button>
        <el-button icon="el-icon-edit" size="small" type="text" v-if="permission.laboratoryReport_edit" @click="rowUpdate(row)">编辑</el-button>
        <el-button icon="el-icon-delete" size="small" type="text" v-if="permission.laboratoryReport_delete" @click="$refs.crud.rowDel(row, index)">删除</el-button>
      </template>
    </avue-crud>
    <el-dialog class="dialog" ref="dialog" :title="dialogTitle" append-to-body :visible.sync="showDialog" :close-on-click-modal="false" top="5vh" @close="closeDialog">
      <avue-form v-if="showDialog" ref="form" v-model="form" :option="dialogOption">
        <template slot="inspectionAttachmentList">
          <el-upload
            v-if="dialogTitle != '详情'"
            class="upload-demo"
            action="/api/blade-resource/oss/endpoint/put-file-attach"
            accept=".png,.jpeg,.jpg,.pdf"
            :headers="headersObj"
            :on-remove="removeFile"
            :on-preview="handlePreview"
            :before-upload="pictureUploadBefore"
            :on-success="pictureUploadSuccess"
            :file-list="pictureList"
            :limit="5"
          >
            <el-button v-if="dialogTitle != '详情'" size="small" type="primary">点击上传</el-button>
            <div v-if="dialogTitle != '详情'" slot="tip" class="el-upload__tip">只能上传png/jpeg/jpg/pdf文件(最多上传5个附件)</div>
          </el-upload>
          <template v-if="dialogTitle === '详情' && pictureList.length > 0">
            <div v-for="(item, index) in pictureList" :key="index">
              <div>{{ item.name }}</div>
              <el-button type="text" icon="el-icon-download" size="small" @click="handleDownload(item.url)">下载</el-button>
            </div>
          </template>
        </template>
      </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="dialogTitle === '新增'" size="small" type="primary" @click="submit"><i class="el-icon-circle-plus-outline"></i><span>保 存</span></el-button>
        <el-button v-if="dialogTitle === '编辑'" size="small" type="primary" @click="submit"><i class="el-icon-circle-check"></i><span>修 改</span></el-button>
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows"></common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, save, remove } from '@/api/quality/laboratory-report';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import website from '@/config/website';
import { Base64 } from 'js-base64';
import { getToken } from '@/util/auth';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';

export default {
  name: 'QualityLaboratoryReport',
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'LABORATORY_REPORT',
      form: {},
      query: {},
      search: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 5,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        searchSpan: 4,
        columnBtn: false,
        column: [
          {
            label: '样品名称',
            prop: 'sampleName'
          },
          {
            label: '样品型号',
            prop: 'sampleModel'
          },
          {
            label: '委托单位',
            prop: 'clientName',
            search: true
          },
          {
            label: '报告编号',
            prop: 'reportNo',
            search: true
          },
          {
            label: '发送日期',
            prop: 'sendDate'
          },
          {
            label: '检测机构',
            prop: 'testingOrg'
          },
          {
            label: '机构地址',
            prop: 'locationName'
          },
          {
            label: '检测',
            prop: 'inspector'
          },
          {
            label: '审核',
            prop: 'auditor'
          },
          {
            label: '批准',
            prop: 'approver'
          },
          {
            label: '测试工程师',
            prop: 'qc'
          },
          {
            label: '技术主管',
            prop: 'leader'
          },
          {
            label: '实验室',
            prop: 'labName'
          }
        ]
      },
      data: [],
      showDialog: false,
      dialogTitle: '新增',
      dialogOption: {
        submitBtn: false,
        emptyBtn: false,
        group: [
          {
            icon: 'el-icon-vertical-bar',
            label: '基本信息',
            arrow: false,
            prop: 'basicInfo',
            column: [
              {
                label: '样品名称',
                prop: 'sampleName',
                rules: [
                  {
                    required: true,
                    message: '请输入样品名称',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '样品型号',
                prop: 'sampleModel',
                rules: [
                  {
                    required: true,
                    message: '请输入样品型号',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '报告编号',
                prop: 'reportNo',
                rules: [
                  {
                    required: true,
                    message: '请输入报告编号',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '委托单位',
                prop: 'clientName',
                rules: [
                  {
                    required: true,
                    message: '请输入委托单位',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '发送日期',
                prop: 'sendDate',
                type: 'datetime',
                format: 'yyyy-MM-dd HH:mm:ss',
                valueFormat: 'yyyy-MM-dd HH:mm:ss',
                rules: [
                  {
                    required: true,
                    message: '请选择发送日期',
                    trigger: 'blur'
                  }
                ]
              }
            ]
          },
          {
            icon: 'el-icon-vertical-bar',
            label: '检测信息',
            arrow: false,
            prop: 'checkInfo',
            column: [
              {
                label: '检测机构',
                prop: 'testingOrg',
                rules: [
                  {
                    required: true,
                    message: '请输入检测机构',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '机构地址',
                prop: 'locationName',
                type: 'search',
                disabled: true,
                appendClick: () => {
                  if (this.dialogTitle === '详情') return;
                  this.openCommonModal();
                },
                rules: [
                  {
                    required: true,
                    message: '请选择机构地址',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '检测',
                prop: 'inspector'
              },
              {
                label: '审核',
                prop: 'auditor'
              },
              {
                label: '批准',
                prop: 'approver'
              },
              {
                label: '测试工程师',
                prop: 'qc'
              },
              {
                label: '技术主管',
                prop: 'leader'
              },
              {
                label: '实验室',
                prop: 'labName'
              }
            ]
          },
          {
            icon: 'el-icon-vertical-bar',
            label: '附件信息',
            arrow: false,
            prop: 'feil',
            column: [
              {
                label: '附件',
                prop: 'inspectionAttachmentList',
                type: 'upload',
                loadText: '附件上传中，请稍等',
                propsHttp: {
                  url: 'link',
                  name: 'originalName',
                  res: 'data'
                },
                limit: 5,
                accept: '.png,.jpeg,.jpg,.pdf',
                tip: '只能上传png/jpeg/jpg/pdf文件',
                action: '/api/blade-resource/oss/endpoint/put-file-attach'
              }
            ]
          }
        ]
      },
      tableOption: {},
      pictureList: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    headersObj() {
      let header = { Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}` };
      header['Blade-Auth'] = 'bearer ' + getToken();
      return header;
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    /**
     * 查看详情数据
     */
    rowView(row) {
      this.showDialog = true;
      this.dialogTitle = '详情';
      this.$nextTick(() => {
        this.$refs.form.allDisabled = true;
      });
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
        this.form.workshopId = '';
        this.pictureList = this._map(this.form.inspectionAttachmentList, (item) => {
          return {
            name: item.attachmentName,
            url: item.link
          };
        });
      });
    },
    rowUpdate(row) {
      this.showDialog = true;
      this.dialogTitle = '编辑';
      this.$nextTick(() => {
        this.$refs.form.allDisabled = false;
      });
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
        this.form.workshopId = '';
        this.pictureList = this._map(this.form.inspectionAttachmentList, (item) => {
          return {
            name: item.attachmentName,
            url: item.link
          };
        });
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    /**
     * 打开新增模态框
     */
    addBtn() {
      this.showDialog = true;
      this.dialogTitle = '新增';
      this.form.workshopId = '';
      this.$nextTick(() => {
        this.$refs.form.allDisabled = false;
      });
    },
    /**
     * 关闭模态框清空表单
     */
    closeDialog() {
      this.$refs.form.resetFields();
      this.form = {};
      this.pictureList = [];
    },
    /**
     * 添加报工单
     */
    submit() {
      this.$refs.form.validate((valid, done) => {
        if (valid) {
          save(this.form).then(
            (res) => {
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: res.data.msg
              });
              this.showDialog = false;
              done();
            },
            (error) => {
              done();
            }
          );
        }
      });
    },
    /**
     * 打开地址选择模态框
     */
    openCommonModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择机构地址信息',
        url: '/api/mes-admin/location/page?status=0',
        isPage: true,
        rowSelectionType: 'single',
        titleInfo: 'locationInfo',
        columnDefs: [
          {
            label: '地址名称',
            prop: 'name',
            search: true
          },
          {
            label: '国家',
            prop: 'countryName'
          },
          {
            label: '省份',
            prop: 'provinceName'
          },
          {
            label: '城市',
            prop: 'cityName'
          },
          {
            label: '详细地址1',
            prop: 'location1'
          },
          {
            label: '详细地址2',
            prop: 'location2'
          },
          {
            label: '详细地址3',
            prop: 'location3'
          },
          {
            label: '详细地址4',
            prop: 'location4'
          },
          {
            label: '邮编',
            prop: 'postCode'
          },
          {
            label: '经度',
            prop: 'latitude'
          },
          {
            label: '纬度',
            prop: 'longitude'
          }
        ]
      };
    },
    /**
     * 选择模态框行数据
     */
    getSelectedRows(rowData) {
      this.form.locationId = rowData.id;
      this.form.locationName = rowData.name;
    },
    handlePreview(file) {
      let url;
      if (file.response) {
        url = this._get(file, 'response.data.link', '');
      } else {
        url = file.url;
      }
      this.$ImagePreview([{ url: url }], 0, {
        closeOnClickModal: false
      });
    },
    pictureUploadSuccess(res) {
      this.form['inspectionAttachmentList'].push({
        attachmentId: res.data.attachId,
        link: res.data.link,
        attachmentName: res.data.originalName
      });
    },
    removeFile(file) {
      this._forEach(this.form.inspectionAttachmentList, (item, index) => {
        if (item.link === file.url) {
          this.form.inspectionAttachmentList.splice(index, 1);
        }
      });
    },
    handleDownload(link) {
      window.open(`${link}`);
    }
  }
};
</script>

<style lang="scss" scoped>
.dialog ::v-deep .avue-form__menu {
  display: none;
}
::v-deep .el-dialog__header {
  padding: 16px 24px;
  min-height: 20px;
  border-bottom: 1px solid #f0f0f0;
}
::v-deep .el-dialog__footer {
  border-top: 1px solid #f0f0f0;
  padding: 10px 16px;
}
.addressRecord {
  height: 32px;
  line-height: 32px;
  vertical-align: middle;
  cursor: pointer;
  padding: 0 5px;
}
.addressRecord:hover {
  background-color: #f5f7fa;
}
</style>
